package cn.wolfcode.ssm.service.impl;

import cn.wolfcode.ssm.domain.Employee;
import cn.wolfcode.ssm.mapper.EmployeeMapper;
import cn.wolfcode.ssm.qo.QueryObject;
import cn.wolfcode.ssm.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public void delete(Long id) {
        //先删自身,在删关联表里数据
        employeeMapper.deleteByPrimaryKey(id);
        employeeMapper.deleteRelation(id);
    }


    @Override
    public void save(Employee employee,Long[] ids) {//ids 角色id的集合
        //在保存员工之前,对密码进行加密
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName());
        employee.setPassword(md5Hash.toString());
        employeeMapper.insert(employee);
        if(ids!=null&&ids.length>0) {
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }


    @Override
    public Employee getOne(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> getAll() {
        return employeeMapper.selectAll();
    }


    @Override
    public void update(Employee employee,Long[] ids) {
        //更新操作,先删除原来的关系,在添加新的关系
        employeeMapper.updateByPrimaryKey(employee);
        employeeMapper.deleteRelation(employee.getId());
        if(ids!=null&&ids.length>0) {
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public PageInfo<Employee> selectForPageResult(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee> employees = employeeMapper.selectForResult(qo);
        return new PageInfo<>(employees);
    }

    @Override
    public Employee login(String username, String password) {
        //查询数据库中是否有能匹配上的数据
        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if (employee == null) { //登录失败
            //抛出运行时异常
            throw new RuntimeException("账号和密码不匹配");
        }
        //将查询出的对象存入session中,供后期登录校验;
        return employee;

    }

    @Override
    public void updatePwd(String newPassword,Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        //将用户名作为盐对密码进行加密
        Md5Hash md5Hash = new Md5Hash(newPassword, employee.getName());
        employeeMapper.updatePwd(md5Hash.toString(),id);
    }

    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }

    @Override
    public Employee selectByName(String name) {
        return employeeMapper.selectByName(name);
    }

    @Override
    public void updateStatus(boolean status,Long id) {
        employeeMapper.updateStatus(status,id);
    }

    @Override
    public Workbook exportXls() {
        //创建excel文件
        Workbook wb = new HSSFWorkbook();
        //创建sheet
        Sheet sheet = wb.createSheet("员工名单");
        //创建第一行
        Row row = sheet.createRow(0);
        //设置内容到单元格中 0 1 2 第一第二第三个单元格
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //查询所有员工数据
        List<Employee> employees = employeeMapper.selectAll();
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            //创建行,每行中保存员工信息
            row = sheet.createRow(i+1);
            //设置内容到单元格中
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        //返回excel文件
        return wb;
    }

    @Override
    public void importXls(MultipartFile file) throws Exception {
        //把接收到的文件转化为excel文件
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第一页
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        //从索引为1的行数开始读(第一行是标题行)
        for (int i = 1; i <= lastRowNum; i++) {
            //获取每行的数据
            Row row = sheet.getRow(i);
            String name = row.getCell(0).getStringCellValue();
            //如果用户名是空，就不再往下读
            if(!StringUtils.hasLength(name.trim())){
                return;
            }
            Employee employee = new Employee();
            employee.setName(name);
            employee.setEmail(row.getCell(1).getStringCellValue());
            //获取文本格式的单元格内容,并设置进employee中
            employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
            //获取数值类型的单元格内容
            //double value = row.getCell(2).getNumericCellValue();
            //employee.setAge((int)value);
            //设置默认密码为1,因为用户添加后要做登录操作
            employee.setPassword("1");
            //调用保存方法
            this.save(employee,null);
        }
    }

    @Override
    public List<Employee> selectByRoleSn(String...sns) {
        return employeeMapper.selectByRoleSn(sns);
    }
}
